package com.vertxExample.starter;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.SqlConnection;
import io.vertx.sqlclient.Tuple;

import java.util.ArrayList;

/**
 *
 */
public class MysqlVerticle extends AbstractVerticle {

	Router router;
	// 1. config mysql
	MySQLConnectOptions connectOptions = new MySQLConnectOptions()
		.setPort(3306)
		.setHost("127.0.0.1")
		.setDatabase("test")
		.setUser("root")
		.setPassword("root");

	// 2. config pool connection
	// Pool options
	PoolOptions poolOptions = new PoolOptions()
		.setMaxSize(5);

	//3. Create the pooled client
	MySQLPool client;

	@Override
	public void start(Promise<Void> startPromise) throws Exception {
		Router router = Router.router(vertx);
		client = MySQLPool.pool(vertx, connectOptions, poolOptions);


		router.route("/test/list").handler(req -> {
			Integer page = Integer.valueOf(req.request().getParam("page"));

			client.getConnection(ar1 -> {
				if (ar1.succeeded()) {
					System.out.println("connected");
					SqlConnection connection = ar1.result();
					var offset = (page - 1) * 4;
					//connection.query("SELECT * FROM users;")
					// sql
					String sql = "SELECT * FROM users limit 4 offset ?";
					System.out.println(sql);
					connection.preparedQuery(sql)
						// 多个参数，添加多个
						//.execute(Tuple.of(offset,offset2), ar2 -> {
						.execute(Tuple.of(offset), ar2 -> {
							if (ar2.succeeded()) {
								var list = new ArrayList<JsonObject>();
								ar2.result().forEach(item -> {
									var json = new JsonObject();
									json.put("id", item.getValue("id"));
									json.put("userName", item.getValue("userName"));
									json.put("passWord", item.getValue("passWord"));
									list.add(json);
								});
								req.response()
									.putHeader("content-type", "application/json")
									.end(
										list.toString()
									);
								/*connection.query("SELECT * FROM users where id = 'emad'")
									.execute(ar3 -> {
										connection.close();
									});*/
							} else {
								connection.close();
							}
						});
				} else {
					System.out.println("connect could not connect:" + ar1.cause().getMessage());
				}
			});

		});

		// config url
		vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
			if (http.succeeded()) {
				startPromise.complete();
				System.out.println("HTTP server started on port 8888");
			} else {
				startPromise.fail(http.cause());
			}
		});
	}
}
